package com.qf.service.impl;

import com.qf.dao.*;
import com.qf.pojo.Address;
import com.qf.pojo.Cart;
import com.qf.pojo.OrderDetail;
import com.qf.pojo.Orders;
import com.qf.service.CartService;
import com.qf.service.OrderService;
import com.qf.util.RandomUtils;

import java.util.Date;
import java.util.List;

/**
 * @author 千锋健哥
 */
public class OrderServiceImpl implements OrderService {

    @Override
    public void create(Integer uid, Integer aid) {
        //1. 根据用户id查询用户购物车列表
        CartService cartService = new CartServiceImpl();
        List<Cart> cartList = cartService.findCartByUid(uid);
        //总价格
        Integer sumMoney = 0;

        //2. 遍历购物车列表, 计算总价格
        if (cartList != null) {
            for (Cart cart : cartList) {
                //计算总价格
                sumMoney = sumMoney + cart.getMoney();
            }
        }

        //3. 创建订单对象
        Orders orders = new Orders();
        //收货地址id
        orders.setAid(aid);
        //用户id
        orders.setUid(uid);
        //总价格
        orders.setMoney(sumMoney);
        //订单创建时间
        orders.setTime(new Date());
        //订单状态, 0 未付款，1已经付款未发货 2发货待收货 3 收货待评价 4订单完成 5 退货状态
        orders.setStatus(0);
        //主键id也是订单号
        orders.setId(RandomUtils.createOrderId());

        //4. 调用dao保存订单
        OrderDao orderDao = new OrderDaoImpl();
        orderDao.insertOrder(orders);

        //5. 保存订单详情
        OrderDetailDao orderDetailDao = new OrderDetailDaoImpl();
        if (cartList != null) {
            for (Cart cart : cartList) {
                OrderDetail orderDetail = new OrderDetail();
                //订单id
                orderDetail.setOid(orders.getId());
                //购买数量
                orderDetail.setNum(cart.getNum());
                //购买的商品id
                orderDetail.setPid(cart.getPid());
                //小计
                orderDetail.setMoney(cart.getMoney());

                orderDetailDao.insert(orderDetail);
            }
        }

        //6. 清空购物车
        cartService.deleteByUid(uid);
    }

    @Override
    public List<Orders> findOrderList(Integer uid) {
        //1. 根据用户id查询用户订单列表
        OrderDao orderDao = new OrderDaoImpl();
        List<Orders> orderList = orderDao.findByUid(uid);

        //2. 遍历订单列表, 根据地址id, 查询地址对象, 放入订单对象中
        AddressDao addressDao = new AddresDaoImpl();
        if (orderList != null) {
            for (Orders orders : orderList) {
                //根据地址id, 查询地址对象
                Address address = addressDao.findById(orders.getAid());
                orders.setAddress(address);
            }
        }

        //3. 将数据返回
        return orderList;
    }

}
